#include "stdafx.h"

#include "TextureLoader.h"
#include "Texture.h"
#include "SOIL/SOIL.h"

using namespace Hiranipra;
using namespace Hiranipra::Platform;
using namespace Hiranipra::Platform::Graphics;
using namespace Hiranipra::Platform::IO;

TextureLoader::TextureLoader( OpenGLDevice* device ) :
	_device( device )
{
}

TextureLoader::~TextureLoader()
{
}

ITexture* TextureLoader::LoadTexture( IO::IFileStream* stream, const TextureLoadOptions options )
{
	MemoryBuffer buffer;
	bool read = stream->ReadAll( buffer );
	DASSERT( read == true, "Unable to read texture from file" );
	if( read == false )
		return NULL;

	int width, height, channels;

	uint32 length;
	void* ptr = buffer.Lock( &length );
	uint8* imageBuffer = SOIL_load_image_from_memory( ( const uint8* )ptr, length, &width, &height, &channels, 0 );
	buffer.Unlock();

	GLuint textureId = SOIL_create_OGL_texture( imageBuffer, width, height, channels, SOIL_CREATE_NEW_ID,
		//SOIL_FLAG_POWER_OF_TWO |
		SOIL_FLAG_MIPMAPS |
		SOIL_FLAG_TEXTURE_REPEATS |
		SOIL_FLAG_MULTIPLY_ALPHA |
		SOIL_FLAG_COMPRESS_TO_DXT |
		SOIL_FLAG_DDS_LOAD_DIRECT
		//SOIL_FLAG_NTSC_SAFE_RGB |
		//SOIL_FLAG_CoCg_Y |
		//SOIL_FLAG_TEXTURE_RECTANGLE |
		);

	DASSERT( textureId != 0, "Unable to create texture" );
	if( textureId == 0 )
		return NULL;

	Texture* texture = new Texture( textureId, width, height, channels );

	return texture;
}
